Page({
  data: {
    userinfo: {},
    openid: ''
  },
  // 授权登录
  onGotUserInfo: function(e) {
    const that = this
    // 登录
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        console.log('云函数调用成功');
        that.setData({
          openid: res.result.openid,
          userinfo: e.detail.userInfo
        })
        that.data.userinfo.openid = that.data.openid
        console.log('userinfo = ', that.data.userinfo);
        wx.setStorageSync('userinfo', that.data.userinfo)
        that.saveLoginMes(e)
      },
      fail: res => {
        console.log('云函数调用失败');
      }
    })
  },
  saveLoginMes: function(e) {
    const ui = wx.getStorageSync('userinfo')
    // 调用后台createuser API
    wx.cloud.callFunction({
      name: 'createuser',
      data: {
        openid: ui.openid,
        date: Date.now(),
        userinfo: ui
      }
    })
  },
  onLoad: function(options) {
    const ui = wx.getStorageSync('userinfo')
    this.setData({
      userinfo: ui,
      openid: ui.openid
    })
  }
})